package com.taoge.p4.common.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Configuration
@Slf4j
public abstract class BaseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 仅处理Controller方法类型的请求
        if (!(handler instanceof HandlerMethod)) {
            return true; // 放行资源请求
        }
        // 记录请求时长，记录请求开始时间，在请求结束的时候拿出这个时间，计算总共耗时
        long startTime = System.currentTimeMillis();
        request.setAttribute("interceptorStartTime", startTime);

        // 打印请求地址
        String servletPath = request.getServletPath();
        log.info("servletPath:{}", servletPath);
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        // 校验token
        validateToken(request, handlerMethod);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    abstract void validateToken(HttpServletRequest request, HandlerMethod handlerMethod);

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        doAfterCompletion();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    abstract void doAfterCompletion();
}
